/**
 * projectName:  
 * fileName:  
 * packageName:  
 * date: 
 * copyright(c) 2017-2020 xxx公司
 */
package cn.horesman.web;

import cn.horesman.service.HoresmanService;
import cn.itcast.mapper.horsemanMapper;
import cn.itcast.pojo.*;
import cn.itcast.pojo.vo.RespBean;
import cn.itcast.util.*;
import cn.web.web_module.util.IconPath;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import static cn.itcast.util.OrderNumber.getOrderIdByTime;

/**
 * @title: homeController.java
 * @package com.job.controller
 * @description: TODO
 * @author: 欧阳辉
 * @date: 2020年3月18日 下午8:57:15
 * @version: V1.0
 */
@Slf4j
@RestController
@RequestMapping(value="/wxshop/horesman",produces = "application/json;charset=UTF-8")
public class HoresmanController {

	@Resource
	HoresmanService horesmanService;
	@Resource
	OutputStringController osc;
	@Resource
	horsemanMapper horsemanMapper;
	@Resource
	CookieUtil cookieUtil;

	@Resource
	cn.itcast.mapper.orderItemMapper orderItemMapper;

	@Resource
	cn.itcast.mapper.orderMapper orderMapper;



	/**
	 * @title:   horseman
	 * @description: 骑手登录
	 * @param:
	 * @throws:
	 */
	@RequestMapping(value="/login", produces = "application/json;charset=UTF-8")
	public String login(@RequestBody Map<String,String> map) {

		String username = map.get("username");
		String password = map.get("password");

		//验证身份
		Map<String,Object> resultMap = horesmanService.login(username,password);
		String results = "";
		if((boolean) resultMap.get("islogin")) {
			results = osc.resultSuccess("yes", resultMap.get("horsemen"));
		}else{
			results = osc.failure("no");
		}
		return results;
	}

	/**
	 * 微信用户登录详情
	 */
	@PostMapping("wxlogin")
	@ResponseBody
	public String user_login(@RequestParam(value = "code", required = false) String code,
							 @RequestParam(value = "horsemanId", required = false) String horsemanId,
							 @RequestParam(value = "rawData", required = false) String rawData,
							 @RequestParam(value = "signature", required = false) String signature,
							 @RequestParam(value = "encrypteData", required = false) String encrypteData,
							 @RequestParam(value = "iv", required = false) String iv) {
		// 用户非敏感信息：rawData
		// 签名：signature
		JSONObject rawDataJson = JSON.parseObject(rawData);
		log.debug(signature);
		// 1.接收小程序发送的code
		// 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
		JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
		// 3.接收微信接口服务 获取返回的参数
		String openid = SessionKeyOpenId.getString("openid");
		log.debug(openid);
		String sessionKey = SessionKeyOpenId.getString("session_key");

		// 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
		String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
		log.debug(signature2);
		if (!signature.equals(signature2)) {
			return osc.resultFailure( "签名校验失败", null);
		}
		// 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
		horseman horseman = horsemanMapper.selectByPrimaryKey(Integer.parseInt(horsemanId));
		// uuid生成唯一key，用于维护微信小程序用户与服务端的会话
		String skey = UUID.randomUUID().toString();


		Map<String,String> map = new HashMap<>();
		map.put("openId",openid);
		map.put("skey",skey);
		String result="";

		if (!StringUtils.isNotBlank(ObjectUtils.toString(horseman.getOpenId()))||!horseman.getOpenId().equals(openid)) {
			// 用户信息入库
			String nickName = rawDataJson.getString("nickName");
			String avatarUrl = rawDataJson.getString("avatarUrl");
			String gender = rawDataJson.getString("gender");
			String city = rawDataJson.getString("city");
			String country = rawDataJson.getString("country");
			String province = rawDataJson.getString("province");

			//horseman = new horseman();
			horseman.setOpenId(openid);
			horseman.setSkey(skey);
			horseman.setCreateTime(new Date());
			horseman.setLastVisitTime(new Date());
			horseman.setSessionKey(sessionKey);
			horseman.setCity(city);
			horseman.setProvince(province);
			horseman.setCountry(country);
			horseman.setAvatarUrl(avatarUrl);
			horseman.setGender((byte) Integer.parseInt(gender));
			horseman.setNickName(nickName);

			horsemanMapper.updateByPrimaryKeySelective(horseman);

			account account = new account();
			account.setOpenId(openid);
			account.setAccountName(rawDataJson.getString("nickName"));
			account.setAccountTypeid(1);
			account.setAccountNumber("0201");

			//创建用户账户
			boolean isCreate = horesmanService.createAccount(account);
			if(isCreate){
				return osc.resultSuccess("登录成功",map);
			}else {
				return osc.resultSuccess("登录成功，账户创建失败",map);
			}

		} else {
			// 已存在，更新用户登录时间
			horseman.setLastVisitTime(new Date());
			// 重新设置会话skey
			horseman.setSkey(skey);
			horsemanMapper.updateByPrimaryKeySelective(horseman);
		}

		result = osc.resultSuccess("登录成功",map);



		//encrypteData比rowData多了appid和openid
		//JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
		//6. 把新的skey返回给小程序

		return result;
	}



	/**
	 *
	 * @Description:
	 * 获取骑手各状态订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findHoresmanOrder")
	public String findHoresmanOrder(@RequestBody Map<String,String> map){
		log.debug("获取骑手各状态订单！！！");
		String orderStatus = map.get("orderStatus");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<order> orders = horesmanService.findHoresmanOrder(orderStatus,openId);
//        PageInfo horesmanOrder = horesmanService.findHoresmanOrder(orderStatus, openId, Integer.parseInt(page));
        if (orders.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取用户各状态订单失败");
		} else {
			results = osc.resultSuccess("yes", orders);
			log.debug("获取用户各状态订单成功");
		}
		return results;
	}

	/**
	 *
	 * @Description:
	 * 骑手接收订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/acceptOrder")
	public String acceptOrder(@RequestBody Map<String,String> map){
		log.debug("骑手接收订单！！！");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		String acceptText = map.get("acceptText");
		//返回结果
		String results ="";
		boolean isaccept= horesmanService.acceptOrder(orderId,acceptText);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("骑手接收订单失败");
		} else {
			results = osc.resultSuccess("yes", "成功接收订单");
			log.debug("骑手接收订单成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 获取单个订单详细信息
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findOneOrder")
	public String findOneOrder(@RequestBody Map<String,String> map){
		log.debug("获取单个订单详细信息！！！");
		String orderId = map.get("orderId");
		//返回结果
		String results ="";
		order order = horesmanService.findOneOrder(orderId);
		if (order==null) {
			results = osc.resultFailure("no", "");
			log.debug("获取单个订单详细信息失败");
		} else {
			results = osc.resultSuccess("yes", order);
			log.debug("获取单个订单详细信息成功");
		}
		return results;

	}



	/**
	 *
	 * @Description:
	 * 骑手确认订单异常
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/abnormalOrder")
	public String abnormalOrder(@RequestBody Map<String,String> map){
		log.debug("骑手确认订单异常");
		//获取地址信息
		Integer orderId =Integer.parseInt(map.get("orderId"));
		String explain =map.get("explain");
		//返回结果
		String results = "";
		boolean isdelect = horesmanService.abnormalOrder(orderId,explain);
		if(isdelect){
			results = osc.success("yes");
			log.debug("骑手确认订单异常成功");
		}else{
			results = osc.failure("no");
			log.debug("骑手确认订单异常失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 骑手取消订单
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/cancelOrder")
	public String cancelOrder(@RequestBody Map<String,String> map){
		System.out.println("aaaaa");
		log.debug("骑手取消订单");
		//获取地址信息
		Integer orderId =Integer.parseInt(map.get("orderId"));
		//返回结果
		String results = "";
		boolean isdelect = horesmanService.cancelOrder(orderId);
		if(isdelect){
			results = osc.success("yes");
			log.debug("骑手取消订单成功");
		}else{
			results = osc.failure("no");
			log.debug("骑手取消订单失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 修改用户数据
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/updateUserInfo")
	public String updateUserInfo(@RequestBody Map<String,String> map){
		log.debug("修改用户数据");
		horseman horseman = new horseman();

		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("openId")))){
			horseman.setOpenId(map.get("openId"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("userName")))){
			horseman.setNickName(map.get("userName"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(Byte.valueOf(map.get("gender"))))){
			horseman.setGender(Byte.valueOf(map.get("gender")));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("phone")))){
			horseman.setHorsemanPhone(map.get("phone"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("userID")))){
			horseman.setHorsemanIdNumber(map.get("userID"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("name")))){
			horseman.setHorsemanName(map.get("name"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("city")))){
			horseman.setCity(map.get("city"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("companyname")))){
			horseman.setCompanyname(map.get("companyname"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("creditcode")))){
			horseman.setCreditcode(map.get("creditcode"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("license")))){
			horseman.setLicense(map.get("license"));
		}

		//返回结果
		String results = "";
		boolean isdelect = horesmanService.updateUserInfo(horseman);
		if(isdelect){
			results = osc.success("yes");
			log.debug("修改用户数据成功");
		}else{
			results = osc.failure("no");
			log.debug("修改用户数据失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 查找用户数据
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findUserInfo")
	public String findUserInfo(@RequestBody Map<String,String> map){
		log.debug("查找用户数据");
		String openId = map.get("openId");

		//返回结果
		String results = "";
		horseman horseman = horesmanService.findUserInfo(openId);
		if(horseman!=null){
			results = osc.resultSuccess("yes",horseman);
			log.debug("查找用户数据成功");
		}else{
			results = osc.failure("no");
			log.debug("查找用户数据失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 修改订单数据（订单称重）
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/updateOrder")
	public String updateOrder(@RequestBody Map<String,String> map){
		log.debug("修改订单数据（订单称重）");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		double price = Double.parseDouble(map.get("price"));
		Date time = new Date();
		order order = new order();
		order.setId(orderId);
		order.setPayOrderMoney(price);
		order.setHorsemanMeasureTime(time);

		//返回结果
		String results = "";
		boolean isdelect = horesmanService.updateOrder(order);
		if(isdelect){
			results = osc.success("yes");
			log.debug("修改订单数据（订单称重）成功");
		}else{
			results = osc.failure("no");
			log.debug("修改订单数据（订单称重）失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 修改订单详细数据（订单称重）
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/updateOrderItem")
	public String updateOrderItem(@RequestBody Map<String,String> map){
		log.debug("修改订单详细数据（订单称重）");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		Integer id = Integer.parseInt(map.get("id"));
		int amount = 0;
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("amount")))){
			amount = Integer.parseInt(map.get("amount"));
		}

		double price = Double.parseDouble(map.get("price"));
		double unitPrice = Double.parseDouble(map.get("unitPrice"));
		double weighWeigh = 0.00;
		double tare = 0.00;
		double finallWeigh = 0.00;
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("weighWeigh")))){
			weighWeigh= Double.parseDouble(map.get("weighWeigh"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("tare")))){
			tare= Double.parseDouble(map.get("tare"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("finallWeigh")))){
			finallWeigh= Double.parseDouble(map.get("finallWeigh"));
		}
		Date time = new Date();
		orderItem orderItem = new orderItem();
		orderItem.setId(id);
		orderItem.setAmount(amount);
		orderItem.setSum(price);
		orderItem.setUnitPrice(unitPrice);
		orderItem.setWeighTime(time);
		orderItem.setWeighWeight(weighWeigh);
		orderItem.setFinallyWeight(finallWeigh);
		orderItem.setNoScalesWeigth(tare);

		//返回结果
		String results = "";
		boolean isdelect = horesmanService.updateOrderItem(orderItem,orderId);
		if(isdelect){
			results = osc.success("yes");
			log.debug("修改订单详细数据（订单称重）成功");
		}else{
			results = osc.failure("no");
			log.debug("修改订单详细数据（订单称重）失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 生成订单
	 * @auther: 欧阳辉
	 * @date: 8:12 2020/3/17
	 * @param: [request]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("uploadOrder")
	public String uploadOrder(HttpServletRequest request) throws IllegalStateException, IOException {
		//返回结果
		String results="";

		//获取订单编号
		Integer id = Integer.parseInt(request.getParameter("id"));


		//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//检查form中是否有enctype="multipart/form-data"
		if(multipartResolver.isMultipart(request))
		{
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
			//获取multiRequest 中所有的文件名
			Iterator iter=multiRequest.getFileNames();

			while(iter.hasNext())
			{
				//一次遍历所有文件
				MultipartFile file=multiRequest.getFile(iter.next().toString());
				if(file!=null)
				{
					SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
					String newDate=sdf.format(new Date());
					//服务器存储图片地址
					//服务器地址：“/usr/tomcat/images/dhn/icon/orderItem”
					//String filePath= "D:/Desktop/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
//					String filePath= "/usr/tomcat/images/dhn/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();	//松注释
					//String filePath="/usr/tomcat/images/wxshop/evaluate/"+request.getParameter("openId")+"/"+file.getOriginalFilename();
//					File files=new File("/usr/tomcat/images/dhn/icon/orderItem/"+newDate);	//松注释

					String filePath= IconPath.ICONPATH +"icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
					File files=new File(IconPath.ICONPATH +"icon/orderItem/"+newDate);
					//File files=new File("D:/Desktop/icon/orderItem/"+newDate);
					if(!files.exists()){//如果文件夹不存在
						files.mkdir();//创建文件夹
					}
					//数据库存放访问地址
					//String path="D:/Desktop/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
					String path="https://www.dhnep.cn:8181/dhn/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
					boolean isadd = horesmanService.addImgPath(path,id);
					if(isadd) {
						//上传图片至服务器
						file.transferTo(new File(filePath));
						results = osc.success("yes");
						log.debug("上传成功");
					}else {
						results = osc.failure("no");
						log.debug("上传失败");
					}

				}

			}

		}
		return results;
	}








	/**
	 *
	 * @Description:
	 * 添加order item
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/addOrderItem")
	public String addOrderItem(@RequestBody Map<String,String> map){
		log.debug("添加order item！！！");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		Integer classifyId = Integer.parseInt(map.get("classifyId"));
		//返回结果
		String results ="";
		boolean isaccept= horesmanService.addOrderItem(orderId,classifyId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("添加order item失败");
		} else {
			results = osc.resultSuccess("yes", "添加order item");
			log.debug("添加order item成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 删除order item
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/delectOrderItem")
	public String delectOrderItem(@RequestBody Map<String,String> map){
		log.debug("删除order item！！！");
		Integer orderId = Integer.parseInt(map.get("id"));
		//返回结果
		String results ="";
		boolean isaccept= horesmanService.delectOrderItem(orderId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("删除order item失败");
		} else {
			results = osc.resultSuccess("yes", "删除order item");
			log.debug("删除order item成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 骑手支付订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/toPayByOrder")
	public String toPayByOrder(@RequestBody Map<String,String> map){
		log.debug("骑手支付订单！！！");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		String openId = map.get("openId");
		double price = Double.parseDouble(map.get("price"));
		//返回结果
		String results ="";
		boolean isaccept= horesmanService.toPayByOrder(orderId,openId,price);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("骑手支付订单失败");
		} else {
			results = osc.resultSuccess("yes", "骑手支付订单");
			log.debug("骑手支付订单成功");
		}
		return results;

	}


	/**
	 * 功能描述: <br>
	 * 〈骑手支付〉
	 * @Author: lyy
	 * @Date: 2020/8/12 10:01
	 * @Param: [map]
	 * @Return: cn.itcast.util.ResponseEntity
	 */
	@PostMapping("/PayByOrderLu")
	public ResponseEntity PayByOrderLu(@RequestBody Map<String,String> map){
		log.debug("骑手支付订单！！！");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		String openId = map.get("openId");
		double price = Double.parseDouble(map.get("price"));
		ResponseEntity responseEntity= horesmanService.PayByOrderLu(orderId,openId,price);
		return responseEntity;

	}


	/**
	 *
	 * @Description:
	 * 更新骑手位置
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/toLatAndLon")
	public String toLatAndLon(@RequestBody Map<String,String> map){
		log.debug("更新骑手位置！！");
		String lat = map.get("lat");
		String lon = map.get("lon");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		boolean isaccept= horesmanService.toLatAndLon(lat,lon,openId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("更新骑手位置失败");
		} else {
			results = osc.resultSuccess("yes", "更新成功");
			log.debug("更新骑手位置成功");
		}
		return results;

	}
	/**
	 *
	 * @Description:
	 * 查找骑手位置
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findHoresmanArea")
	public String findHoresmanArea(@RequestBody Map<String,String> map){
		log.debug("查找骑手位置！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		horseman horesman= horesmanService.findHoresmanArea(openId);
		if (horesman==null) {
			results = osc.resultFailure("no", "");
			log.debug("查找骑手位置失败");
		} else {
			results = osc.resultSuccess("yes", horesman);
			log.debug("查找骑手位置成功");
		}
		return results;

	}



	/**
	 *功能：获取所有商家数据
	 * @author 欧阳辉
	 * @date 2019/6/18
	 * @param
	 * @return java.lang.String
	 */
	@PostMapping("/getAllMerchant")
	public String getAllMerchant(@RequestBody Map<String,String> map){
		log.debug("获取所有商家数据");
		//返回结果
		String results ="";
		//获取页数
		Integer pageNum = Integer.parseInt(map.get("page"));
		//获取每页大小
		Integer pageSize = Integer.parseInt(map.get("limit"));
		//查询类型
		String select = "";
		if(StringUtils.isNotBlank(map.get("select"))){
			select = map.get("select");
		}
		//查询值
		String value = "";
		if(StringUtils.isNotBlank(map.get("value"))){
			value = map.get("value");
		}
		List<merchant> merchants = horesmanService.getAllMerchant(pageNum,pageSize,select,value);
		if(merchants.isEmpty()){
			results = osc.resultFailure("no","");
			log.debug("获取所有商家数据失败");
		}else {
			// 取分页信息
			PageInfo<merchant> pageInfo = new PageInfo<merchant>(merchants);
			long total = pageInfo.getTotal(); //获取总记录数
			results = osc.resultSuccess("yes",merchants,total);
			log.debug("获取所有骑手数据成功");
		}

		return results;
	}


	/**
	 *功能：获取所有商家数据
	 * @author 欧阳辉
	 * @date 2019/6/18
	 * @param
	 * @return java.lang.String
	 */
	@PostMapping("/selectAllIsopenMerchant")
	public String selectAllIsopenMerchant(@RequestBody Map<String,String> map){
		log.debug("获取所有商家数据");
		//返回结果
		String results ="";
		//获取页数
		Integer pageNum = Integer.parseInt(map.get("page"));
		//获取每页大小
		Integer pageSize = Integer.parseInt(map.get("limit"));
		List<merchant> merchants = horesmanService.selectAllIsopenMerchant(pageNum,pageSize);
		if(merchants.isEmpty()){
			results = osc.resultFailure("no","");
			log.debug("获取所有商家数据失败");
		}else {
			// 取分页信息
			PageInfo<merchant> pageInfo = new PageInfo<merchant>(merchants);
			long total = pageInfo.getTotal(); //获取总记录数
			results = osc.resultSuccess("yes",merchants,total);
			log.debug("获取所有骑手数据成功");
		}
		return results;
	}


	/**
	 *
	 * @Description:
	 * 打包
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/packgeOrder")
	public String packgeOrder(@RequestBody Map<String,String> map){
		log.debug("打包！！");
		String horesmanOpenId = map.get("horesmanOpenId");
		String merchantOpenId = map.get("merchantOpenId");
		String[] ids = map.get("orderItem").split(",");
		String name = map.get("merchantName");
		//返回结果
		String results ="";
		boolean ispackge= horesmanService.packgeOrder(horesmanOpenId,merchantOpenId,ids,name);
		if (!ispackge) {
			results = osc.resultFailure("no", "");
			log.debug("打包失败");
		} else {
			results = osc.resultSuccess("yes", "");
			log.debug("打包成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 获取骑手待打包状态订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findPackageType")
	public String findPackageType(@RequestBody Map<String,String> map){
		log.debug("获取骑手待打包状态订单！！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<String> orders = horesmanService.findPackageType(openId);
		if (orders.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取骑手待打包状态订单失败");
		} else {
			results = osc.resultSuccess("yes", orders);
			log.debug("获取骑手待打包状态订单成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 获取骑手待打包状态订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findPackageOrder")
	public String findPackageOrder(@RequestBody Map<String,String> map){
		log.debug("获取骑手待打包状态订单！！！");
		String openId = map.get("openId");
		String type = map.get("type");
		//返回结果
		String results ="";
		List<order> orders = horesmanService.findPackageOrder(openId,type);
		if (orders.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取骑手待打包状态订单失败");
		} else {
			results = osc.resultSuccess("yes", orders);
			log.debug("获取骑手待打包状态订单成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 获取骑手打包后的新订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findAllPackageOrder")
	public String findAllPackageOrder(@RequestBody Map<String,String> map){
		log.debug("获取骑手待打包状态订单！！！");
		String openId = map.get("openId");
		String status = map.get("status");
		//返回结果
		String results ="";
		List<packageOrder> packageOrders = horesmanService.findAllPackageOrder(status,openId);
		if (packageOrders.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取骑手待打包状态订单失败");
		} else {
			results = osc.resultSuccess("yes", packageOrders);
			log.debug("获取骑手待打包状态订单成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 骑手取消订单
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/cancelPackageOrder")
	public String cancelPackageOrder(@RequestBody Map<String,String> map){
		System.out.println("aaa");
		log.debug("骑手取消订单");
		//获取地址信息
		Integer orderId =Integer.parseInt(map.get("orderId"));
		//返回结果
		String results = "";
		boolean isdelect = horesmanService.cancelPackageOrder(orderId);
		if(isdelect){
			results = osc.success("yes");
			log.debug("骑手取消订单成功");
		}else{
			results = osc.failure("no");
			log.debug("骑手取消订单失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 生成订单
	 * @auther: 欧阳辉
	 * @date: 8:12 2020/3/17
	 * @param: [request]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("addOrder")
	public String addOrder(@RequestBody Map<String,String> map) {
		//返回结果
		String results="";
		packageOrder packageOrder = new packageOrder();
		if(StringUtils.isBlank(map.get("productType"))){
			return results = osc.failure("no");
		}
		if(StringUtils.isBlank(map.get("productId"))){
			return results = osc.failure("no");
		}
		log.debug("添加订单开始");
		String orderNumber = getOrderIdByTime();
		packageOrder.setOldIds("线下订单");
		packageOrder.setOrderNumber(orderNumber);
		packageOrder.setOrderTime(new Date());
		packageOrder.setProductType(map.get("productType"));
		packageOrder.setOrderExplain(map.get("explain"));
		packageOrder.setOpenId(map.get("openId"));
		packageOrder.setRecycleName(map.get("merchantName"));
		packageOrder.setRecycleNumber(map.get("merchantNumber"));
		packageOrder.setRecycleAddress(map.get("merchantArea"));

		boolean isadd = horesmanService.addOrder(packageOrder,map.get("productId"));
		if(isadd) {
			results = osc.resultSuccess("yes",orderNumber);
			log.debug("添加订单成功");
		}else {
			results = osc.failure("no");
			log.debug("添加订单失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 查看用户所有收益
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findTypeEarnings")
	public String findTypeEarnings(@RequestBody Map<String,String> map){
		log.debug("查看用户所有收益");
		String openId = map.get("openId");

		//返回结果
		String results = "";
		Map<String, List<earnings>> earnings = horesmanService.findAllEarnings(openId);
		if(!earnings.isEmpty()){
			results = osc.resultSuccess("yes",earnings);
			log.debug("查看用户所有收益成功");
		}else{
			results = osc.failure("no");
			log.debug("查看用户所有收益失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 查看骑手星级
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findHoresmanStarLever")
	public String findHoresmanStarLever(@RequestBody Map<String,String> map){
		log.debug("查看骑手星级");
		String openId = map.get("openId");

		//返回结果
		String results = "";
		horseman horesman = horesmanService.findHoresmanStarLever(openId);
		if(horesman!=null){
			results = osc.resultSuccess("yes",horesman);
			log.debug("查看骑手星级成功");
		}else{
			results = osc.failure("no");
			log.debug("查看骑手星级失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 申请增重
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/applyAdd")
	public String applyAdd(@RequestBody Map<String,String> map){
		log.debug("申请增重");
		String openId = map.get("openId");
		String orderId = map.get("orderId");

		//返回结果
		String results = "";
		boolean isapply = horesmanService.applyAdd(openId,orderId);
		if(isapply){
			results = osc.success("yes");
			log.debug("申请增重成功");
		}else{
			results = osc.failure("no");
			log.debug("申请增重失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 审核
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/apply")
	public String apply(@RequestBody Map<String,String> map){
		log.debug("审核");
		String openId = map.get("openId");
		String orderId = map.get("orderId");

		//返回结果
		String results = "";
		boolean isapply = horesmanService.apply(orderId);
		if(isapply){
			results = osc.success("yes");
			log.debug("审核成功");
		}else{
			results = osc.failure("no");
			log.debug("审核失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 骑手注册验证验证码
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/toCode")
	public String toCode(@RequestBody Map<String,String> map){
		log.debug("骑手注册验证验证码");
		int code = Integer.parseInt(map.get("code"));
		String phone = map.get("phone");

		//返回结果
		String results = "";
		boolean isapply = horesmanService.toCode(code,phone);
		if(isapply){
			results = osc.success("yes");
			log.debug("骑手注册验证验证码成功");
		}else{
			results = osc.failure("no");
			log.debug("骑手注册验证验证码失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 验证驾驶证
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/getHoresmanToken")
	public String getHoresmanToken(@RequestBody Map<String,String> map){
		log.debug("验证驾驶证");

		//返回结果
		String results = "";
		String token = horesmanService.getHoresmanToken();
		if(token!=null){
			results = osc.resultSuccess("yes",token);
			log.debug("验证驾驶证成功");
		}else{
			results = osc.failure("no");
			log.debug("验证驾驶证失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 骑手注册申请
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/register")
	public String register(@RequestBody Map<String,String> map){
		log.debug("骑手注册申请");
		String name = map.get("name");
		String phone = map.get("phone");
		String pssword = map.get("pssword");
		String idName = map.get("idName");
		String idCard = map.get("idCard");
		String idTime = map.get("idTime");
		String carClass = map.get("carClass");
		String validTo = map.get("validTo");
		String validFrom = map.get("validFrom");

		horseman horseman = new horseman();
		horseman.setHorsemanName(idName);
		horseman.setHorsemanPassword(pssword);
		horseman.setHorsemanNumber(phone);
		horseman.setHorsemanPhone(phone);
		horseman.setHorsemanIdNumber(idCard);
		horseman.setHorsemanIdNumberTime(idTime);
		horseman.setHorsemanRegisterTime(new Date());
		horseman.setHorsemanCarClass(carClass);
		horseman.setHorsemanValidTo(validTo);
		horseman.setHorsemanValidFrom(validFrom);
		//返回结果
		String results = "";
		boolean isapply = horesmanService.register(horseman);
		if(isapply){
			results = osc.success("yes");
			log.debug("骑手注册申请成功");
		}else{
			results = osc.failure("no");
			log.debug("骑手注册申请失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 查询个人今日收货额
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/todayCount")
	public String todayCount(@RequestBody Map<String,String> map){
		log.debug("查询个人今日收货额");

		String openId = map.get("openId");

		//返回结果
		String results = "";
		double count = horesmanService.todayCount(openId);
		if(count!=0){
			results = osc.resultSuccess("yes",count);
			log.debug("查询个人今日收货额成功");
		}else{
			results = osc.failure("no");
			log.debug("查询个人今日收货额失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 查询个人昨日收货额
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/yesterdayCount")
	public String yesterdayCount(@RequestBody Map<String,String> map){
		log.debug("查询个人今日收货额");

		String openId = map.get("openId");

		//返回结果
		String results = "";
		double count = horesmanService.yesterdayCount(openId);
		if(count!=0){
			results = osc.resultSuccess("yes",count);
			log.debug("查询个人今日收货额成功");
		}else{
			results = osc.failure("no");
			log.debug("查询个人今日收货额失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 查询个人今日订单数量
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/orderTodayCount")
	public String orderTodayCount(@RequestBody Map<String,String> map){
		log.debug("查询个人今日收货额");

		String openId = map.get("openId");

		//返回结果
		String results = "";
		double count = horesmanService.orderTodayCount(openId);
		if(count!=0){
			results = osc.resultSuccess("yes",count);
			log.debug("查询个人今日订单数量成功");
		}else{
			results = osc.failure("no");
			log.debug("查询个人今日订单数量失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 查询个人昨日订单数量
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/orderYesterdayCount")
	public String orderYesterdayCount(@RequestBody Map<String,String> map){
		log.debug("查询个人昨日订单数量");

		String openId = map.get("openId");

		//返回结果
		String results = "";
		double count = horesmanService.orderYesterdayCount(openId);
		if(count!=0){
			results = osc.resultSuccess("yes",count);
			log.debug("查询个人昨日订单数量成功");
		}else{
			results = osc.failure("no");
			log.debug("查询个人昨日订单数量失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 查询个人今日订单货物重量
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/orderTodayWeight")
	public String orderTodayWeight(@RequestBody Map<String,String> map){
		log.debug("查询个人今日订单货物重量");

		String openId = map.get("openId");

		//返回结果
		String results = "";
		double count = horesmanService.orderTodayWeight(openId);
		if(count!=0){
			results = osc.resultSuccess("yes",count);
			log.debug("查询个人今日订单货物重量成功");
		}else{
			results = osc.failure("no");
			log.debug("查询个人今日订单货物重量失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 查询个人昨日订单货物重量
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/orderYesterdayWeight")
	public String orderYesterdayWeight(@RequestBody Map<String,String> map){
		log.debug("查询个人昨日订单货物重量");

		String openId = map.get("openId");

		//返回结果
		String results = "";
		double count = horesmanService.orderYesterdayWeight(openId);
		if(count!=0){
			results = osc.resultSuccess("yes",count);
			log.debug("查询个人昨日订单货物重量成功");
		}else{
			results = osc.failure("no");
			log.debug("查询个人昨日订单货物重量失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 获取打包分类
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/5/9
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findPackageClassify")
	public String findPackageClassify(@RequestBody Map<String,String> map){
		log.debug("获取打包分类");


		//返回结果
		String results = "";
		List<Map<String,Object>> packageClassifys = horesmanService.findPackageClassify();
		if(packageClassifys.isEmpty()){
			results = osc.failure("no");
			log.debug("获取打包分类失败");
		}else{
			results = osc.resultSuccess("yes",packageClassifys);
			log.debug("获取打包分类成功");

		}

		return results;
	}


	/**
	 * 大件物品，骑手确认到达
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/orderConfirm")
	public String orderConfirm(@RequestBody Map<String,String> map){
		//返回结果
		String results = "";
		Integer orderId = Integer.parseInt(map.get("orderId"));
		orderExample rEx = new orderExample();
		orderExample.Criteria criteria = rEx.createCriteria();
		criteria.andIdEqualTo(orderId);
		List<cn.itcast.pojo.order> orders = orderMapper.selectByExample(rEx);
		if(orders!=null&&orders.size()>0){
			order order = orders.get(0);
			order.setOrderState("待支付");
			int i = orderMapper.updateByPrimaryKeySelective(order);
			log.debug("修改订单详细数据（确认到达）成功");
			boolean flag = orderItem(map.get("orderId"));
			results = osc.success("确认到达成功 修改失败");
		}else{
			log.debug("修改订单详细数据（确认到达）失败");
			results = osc.failure("确认到达失败");
		}
		return results;
	}

	public boolean orderItem(String orderId){
		orderItemExample rEx = new orderItemExample();
		orderItemExample.Criteria criteria = rEx.createCriteria();
		criteria.andOrderIdEqualTo(Integer.parseInt(orderId));
		List<cn.itcast.pojo.orderItem> orderItems = orderItemMapper.selectByExample(rEx);
		if(orderItems.isEmpty()){
			return false;
		}else {
			ArrayList<Integer> itemId = new ArrayList<>();
			for (int i = 0;i<orderItems.size();i++){
				itemId.add(orderItems.get(i).getId());
			}
			for (Integer itemID:itemId){
				orderItem orderItem = orderItemMapper.selectByPrimaryKey(itemID);
				orderItem.setWeighWeight(0.00);
				orderItem.setNoScalesWeigth(0.00);
				orderItem.setFinallyWeight(0.00);
				orderItem.setUnitPrice(0.00);
				orderItem.setAmount(0);
				orderItem.setSum(0.00);
				Date time = new Date();
				orderItem.setWeighTime(time);
				orderItemMapper.updateByPrimaryKeySelective(orderItem);
			}
			return true;
		}
	}
}